/**
 * 教学班视角-课表单元
 * @param  {[type]} jxbTimeItem [description]
 * @return {[type]}              [description]
 */
define(function(require) {

    // 其他模块引用的对象将作为属性统一放到_module中
    var _module = {
        commonLib: require('./commonLib'),
        conflictValidator: require('./conflictValidator'),
        zeroModal: require('../../zeroModal/zeroModal'),
    };

    var jxbTimeItem = {

        /**
         * 根据星期、节次、节次模式构建教学班课表单元的HTML内容
         * @param  {[type]} weeks    [description]
         * @param  {[type]} units    [description]
         * @param  {[type]} unitMode [description]
         * @return {[type]}          [description]
         */
        buildItemHtml: function(weeks, units, unitMode) {
            var avgWidth = Math.round(92 / weeks.length);

            // 构建header
            var _html = '<tr>';
            _html += '      <td>节次/星期</td>';
            for (var i = 0; i < weeks.length; i++) {
                var _w = weeks[i];
                _html += '  <td class="mtt_fontsize13" style="width:' + avgWidth + '%" data-week="' + _w.code + '">' + _w.name + '</td>';
            }
            _html += '</tr>';

            // 构建item
            var _rowIndex = 0;
            for (var i = 0; i < units.length; i++) {
                var _u = units[i];
                _html += ' <tr>';
                _html += '  <td class="mtt_fontsize13" data-unit="' + _u.code + '">' + _u.name + '</td>';

                for (var j = 0; j < weeks.length; j++) {
                    // 如果节次模式是多节
                    if (unitMode > 1) {
                        // 判断当前列对应的rowspan下标是否为0，为0表示第一列，其他的则不拼td
                        if (_rowIndex === 0) {
                            _html += '<td data-role="item" data-week="' + weeks[j].code + '" data-begin-unit="' + _u.code + '" data-end-unit="' + (parseInt(_u.code) + unitMode - 1) + '" ';
                            _html += 'rowspan=' + unitMode + '>';
                            _html += '</td>';
                        }
                    } else {
                        _html += '<td data-role="item" data-week="' + weeks[j].code + '" data-begin-unit="' + _u.code + '" data-end-unit="' + _u.code + '"></td>';
                    }
                }
                // 每循环一次节次列表，rowspan的下标+1，如果rowspan的下标等于节次数了，则重新初始化rowspan的下标值
                _rowIndex++;
                if (_rowIndex === unitMode) {
                    _rowIndex = 0;
                }
                _html += '</tr>';
            }

            return _html;
        },

        /**
         * 给item绑定事件(绑定节次星期表格单元格的事件)
         * @return {[type]} [description]
         */
        bindItemEvent: function(jxbTimeTable) {
            var _current = jxbTimeTable._current;

            /**
             * 绑定单元格鼠标移入移除的事件
             * 移入时显示添加课程安排的图标
             */
            $('[data-role="item"]').mouseenter(function(e) {
                var jobj = $(this);
                var week = jobj.attr('data-week');
                var beginUnit = jobj.attr('data-begin-unit');
                var endUnit = jobj.attr('data-end-unit');

                // 检查当前单元格是否已有排课结果
                var _arrangedItems = _module.commonLib.getArranges(_current.arranges, week, beginUnit, endUnit);
                if (_arrangedItems.length > 0) {
                    _current.itemToAdd = undefined;
                    return;
                }
                // 检查当前单元格是否为屏蔽区域
                var _obstacles = _module.commonLib.getObstacles(_current.obstacles, _current.opt.weekNum, week, beginUnit, endUnit);
                if (_obstacles.length > 0) {
                    return;
                }

                _current.itemToAdd = jobj;

                // 构建添加课程安排的元素，并绑定点击事件
                var jaddDom = $('<div class="mtt_add_container"><i class="icon iconfont mtt_add"></i></div>');
                jaddDom.click(function() {
                    if (typeof _current.opt.weekNum === 'undefined') {
                        _module.zeroModal.alert('请先选择周次！');
                        return;
                    }
                    // 开始添加新的排课结果
                    _current.arranges.push({
                        jxbid: _current.jxbInfo.jxbid,
                        jxbmc: _current.jxbInfo.jxbmc,
                        teacherId: '',
                        teacherName: '',
                        classroomId: '',
                        classroomName: '',
                        weekNum: _current.opt.weekNum,
                        weekName: _current.opt.weekName,
                        week: week,
                        beginUnit: beginUnit,
                        endUnit: endUnit
                    });
                    // 重新渲染排课结果
                    jxbTimeTable.renderArranges();
                    this.remove();
                });
                $(this).append(jaddDom);


            }).mouseleave(function(e) {
                // 鼠标移出时清除添加课程安排的元素
                if (_current.itemToAdd !== undefined) {
                    _current.itemToAdd.find('.mtt_add_container').remove();
                }
            });

            /**
             * 绑定拖动排课结果时，经过单元格的事件
             */
            $('[data-role="item"]').drop(function(e) {
                var jobj = $(this);

                // 获取移动后的位置信息
                var movedPosition = {
                    week: jobj.attr('data-week'),
                    beginUnit: jobj.attr('data-begin-unit'),
                    endUnit: jobj.attr('data-end-unit')
                };

                // 验证当前位置是否为禁排区域
                var _obstacles = _module.commonLib.getObstacles(_current.obstacles, _current.opt.weekNum, movedPosition.week, movedPosition.beginUnit, movedPosition.endUnit);
                if (_obstacles.length > 0) {
                    _module.zeroModal.alert({
                        content: '该时间段禁止排课！',
                        contentDetail: _obstacles[0].description
                    });
                    return;
                }

                // 冲突检测
                // 1. 前台验证冲突
                var frontChecker = function() {
                    var deferred = $.Deferred();
                    var conflict = _module.conflictValidator.validateByJxbView(_current.arranges, _current.movingArrange, movedPosition);

                    var data = {
                        currentArrange: _current.movingArrange,
                        movedPosition: movedPosition
                    };
                    if (conflict !== undefined) {
                        _module.zeroModal.confirm({
                            content: conflict + '，强制安排吗？',
                            okFn: function() {
                                deferred.resolve(data);
                            }
                        });
                    } else {
                        deferred.resolve(data);
                    }
                    return deferred;
                };
                // 2. 后台验证冲突
                var backChecker = _current.opt.conflictChecker;
                // 开始验证
                frontChecker().then(backChecker).then(function(data) {
                    if (data === 1) {
                        jxbTimeTable.movedArrage(movedPosition);
                    }
                });
            });
        }

    };

    return jxbTimeItem;

});
